package com.situ.vivamarket.api.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.situ.vivamarket.model.Order;
import com.situ.vivamarket.model.OrderState;
import com.situ.vivamarket.model.search.OrderSearchBean;
import com.situ.vivamarket.service.front.MemberAddrService;
import com.situ.vivamarket.service.OrderService;
import com.situ.vivamarket.util.JsonResult;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/api/v1/order")
public class OrderApi {
    private OrderService orderService;
    private MemberAddrService memberAddrService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
    @Autowired
    public void setMemberAddrService(MemberAddrService memberAddrService) {
        this.memberAddrService = memberAddrService;
    }

    //  获取订单数据
    @GetMapping
    public ResponseEntity<JsonResult> list(OrderSearchBean osb,
                                           @RequestParam(defaultValue = "1") Integer page,
                                           @RequestParam (defaultValue = "10") Integer limit)
    {
        Page<?> p =new Page<>(page,limit);

        List<Order> orders=orderService.getAllOrders(osb,p);
        PageInfo<Order> pi=new PageInfo<>(orders);
        JsonResult result=JsonResult.successData(orders);
        result.setCount((int) pi.getTotal());
        return ResponseEntity.ok(result);
    }
    @DeleteMapping
    public ResponseEntity<JsonResult> deleteByIds(@Validated @NotNull @Size(min = 1, message = "至少删除一个元素")
                                                      Integer[] ids) {
        int rows = this.orderService.deleteByIds(ids);
        if (rows > 0) {
            return ResponseEntity.ok(JsonResult.successData(rows));
        } else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }

    //发货
    @PatchMapping("/ship")
    public ResponseEntity<JsonResult> ship(Integer id) {
        Order db = this.orderService.findById(id);
        if (db == null) {
            return ResponseEntity.ok(JsonResult.fail("要发货的订单不存在"));
        }

        if (db.getState() != OrderState.PAYED) {
            return ResponseEntity.ok(JsonResult.fail("只能对已支付的订单发货"));
        }

        Order order = new Order();
        order.setId(id);
        order.setState(OrderState.SHIPPED);//设置为已发货

        boolean success = this.orderService.patch(order);//部分修改

        if (success) {
            return ResponseEntity.ok(JsonResult.success("发货成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("发货失败"));
        }
    }


    //收货
    @PatchMapping("/receive")
    public ResponseEntity<JsonResult> receive(Integer id) {
        Order db = this.orderService.findById(id);
        if (db == null) {
            return ResponseEntity.ok(JsonResult.fail("要收货的订单不存在"));
        }

        if (db.getState() != OrderState.SHIPPED) {
            return ResponseEntity.ok(JsonResult.fail("只能对已发货的订单收货"));
        }

        Order order = new Order();
        order.setId(id);
        order.setState(OrderState.RECEIVED);//设置为已发货

        boolean success = this.orderService.patch(order);//部分修改

        if (success) {
            return ResponseEntity.ok(JsonResult.success("收货成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("收货(后台)失败"));
        }
    }

    //修改订单状态为退款中
    @PatchMapping("/refunding")
    public ResponseEntity<JsonResult> refunding(Integer id) {
        Order db = this.orderService.findById(id);
        if (db == null) {
            return ResponseEntity.ok(JsonResult.fail("要申请退款的订单不存在"));
        }

        if (db.getState() == OrderState.CREATED) {
            return ResponseEntity.ok(JsonResult.fail("不能对未付款的订单申请退款"));
        }
        if(db.getState() == OrderState.REFUNDING||db.getState() == OrderState.REFUNDED){
            return ResponseEntity.ok(JsonResult.fail("不能对退款中或已退款的订单申请退款"));
        }

        Order order = new Order();
        order.setId(id);
        order.setState(OrderState.REFUNDING);//设置为已发货

        boolean success = this.orderService.patch(order);//部分修改

        if (success) {
            return ResponseEntity.ok(JsonResult.success("申请退款成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("申请退款失败"));
        }
    }
    @PatchMapping("/refunded")
    public ResponseEntity<JsonResult> refunded(Integer id) {
        Order db = this.orderService.findById(id);
        if (db == null) {
            return ResponseEntity.ok(JsonResult.fail("要退款的订单不存在"));
        }

        if (db.getState() != OrderState.REFUNDING) {
            return ResponseEntity.ok(JsonResult.fail("只能对退款中的订单退款"));
        }


        Order order = new Order();
        order.setId(id);
        order.setState(OrderState.REFUNDED);//设置为已退款

        boolean success = this.orderService.patch(order);//部分修改

        if (success) {
            return ResponseEntity.ok(JsonResult.success("退款成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("退款失败"));
        }
    }
//    后台修改订单数据
    @PutMapping
    public ResponseEntity<JsonResult> update(@RequestBody Map<String, Object> reqb) {
        Integer streetId = (Integer) reqb.get("streetId");
        String ndetail = (String) reqb.get("ndetail");
        BigDecimal totalPay = new BigDecimal(reqb.get("totalPay").toString());
//      设置order接收参数
        Order order = new Order();
        order.setId((Integer) reqb.get("id"));
        order.setNote((String) reqb.get("note"));
        order.setReceiverPhone((String) reqb.get("receiverPhone"));
        order.setTotalPay(totalPay);
        if(streetId!=null&&ndetail!=null){
            String parts=this.orderService.findFullNameById(streetId);
            order.setReceiverAddrDetail(parts+ndetail);
        }
        boolean success=orderService.patch(order);
        if(success){
            return ResponseEntity.ok(JsonResult.successData(order));
        }else{
            return ResponseEntity.internalServerError().body(JsonResult.fail("修改订单异常"));
        }
    }
}